<template>
  <div class="appointment-confirm-page">
    <!-- 顶部导航栏 -->
    <div class="header">
      <div class="header-content">
        <div class="back-btn" @click="$router.go(-1)">
          <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="#fff" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
            <path d="M15 18l-6-6 6-6"/>
          </svg>
        </div>
        <div class="header-title">预约确认</div>
        <div class="home-btn" @click="$router.push('/')">
          <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="#fff" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
            <path d="M3 9l9-7 9 7v11a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z"/>
            <polyline points="9,22 9,12 15,12 15,22"/>
          </svg>
        </div>
      </div>
    </div>

    <!-- 页面内容 -->
    <div class="content">
      <div class="success-icon">
        <svg width="60" height="60" viewBox="0 0 24 24" fill="none" stroke="#4CAF50" stroke-width="2">
          <path d="M22 11.08V12a10 10 0 1 1-5.93-9.14"/>
          <polyline points="22,4 12,14.01 9,11.01"/>
        </svg>
      </div>

      <h1 class="title">预约成功</h1>
      <p class="subtitle">您的预约信息已确认</p>

      <!-- 预约信息 -->
      <div class="appointment-info" v-if="appointmentData">
        <div class="info-card">
          <h3>医生信息</h3>
          <div class="doctor-info">
            <div class="doctor-avatar">
              <img 
                :src="appointmentData.doctor.avatar" 
                :alt="appointmentData.doctor.name"
                @error="handleImageError"
              />
            </div>
            <div class="doctor-details">
              <h4>{{ appointmentData.doctor.name }}</h4>
              <p>{{ appointmentData.doctor.department }}</p>
              <p>{{ appointmentData.doctor.hospital }}</p>
            </div>
          </div>
        </div>

        <!-- 收货地址 -->
        <div class="info-card">
          <h3>收货地址</h3>
          <div class="address-info" @click="showAddressMap = true">
            <div class="address-icon">
              <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                <path d="M12 2C8.13 2 5 5.13 5 9c0 5.25 7 13 7 13s7-7.75 7-13c0-3.87-3.13-7-7-7z"/>
                <circle cx="12" cy="9" r="2.5"/>
              </svg>
            </div>
            <div class="address-content">
              <div class="address-detail">{{ selectedAddress || '请选择收货地址' }}</div>
            </div>
            <div class="address-arrow">
              <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                <path d="M9 18l6-6-6-6"/>
              </svg>
            </div>
          </div>
        </div>

        <div class="info-card">
          <h3>预约时间</h3>
          <div class="time-info">
            <div class="date-display">
              <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                <rect x="3" y="4" width="18" height="18" rx="2" ry="2"/>
                <line x1="16" y1="2" x2="16" y2="6"/>
                <line x1="8" y1="2" x2="8" y2="6"/>
                <line x1="3" y1="10" x2="21" y2="10"/>
              </svg>
              <span>{{ formatDate(appointmentData.date) }}</span>
            </div>
            <div class="time-display">
              <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                <circle cx="12" cy="12" r="10"/>
                <polyline points="12,6 12,12 16,14"/>
              </svg>
              <span>{{ formatTime(appointmentData.time) }}</span>
            </div>
          </div>
        </div>

                 <div class="info-card" v-if="appointmentData.patient">
           <h3>就诊人信息</h3>
           <div class="patient-info">
             <div class="patient-avatar">
               <img 
                 :src="appointmentData.patient.avatar" 
                 :alt="appointmentData.patient.name"
                 @error="handleImageError"
               />
             </div>
             <div class="patient-details">
               <h4>{{ appointmentData.patient.name }}</h4>
               <p>出生日期：{{ appointmentData.patient.birthDate }}</p>
               <p>性别：{{ appointmentData.patient.gender === 'male' ? '男' : '女' }}</p>
             </div>
           </div>
         </div>

         <div class="info-card">
           <h3>预约编号</h3>
           <div class="appointment-id">
             <span>{{ appointmentId }}</span>
           </div>
         </div>
      </div>

      <!-- 注意事项 -->
      <div class="notice-card">
        <h3>注意事项</h3>
        <ul class="notice-list">
          <li>请提前15分钟到达医院</li>
          <li>请携带有效身份证件</li>
          <li>如有特殊情况请提前联系医院</li>
          <li>预约成功后请按时就诊</li>
        </ul>
      </div>
    </div>

    <!-- 底部按钮 -->
    <div class="bottom-button">
      <button class="pay-btn" @click="goToPayment">
        立即支付
      </button>
      <div class="secondary-buttons">
        <button class="home-btn-secondary" @click="$router.push('/')">
          返回首页
        </button>
        <button class="view-appointments-btn" @click="viewAppointments">
          查看我的预约
        </button>
      </div>
    </div>

    <!-- 地址选择组件 -->
    <AddressMap
      v-model:visible="showAddressMap"
      @select-address="handleAddressSelect"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import AddressMap from '@/components/AddressMap.vue'

const router = useRouter()

interface Doctor {
  _id: string
  name: string
  department: string
  avatar: string
  hospital: string
}

interface Patient {
  id: string
  name: string
  birthDate: string
  gender: 'male' | 'female'
  idCard: string
  phone: string
  avatar: string
}

interface AppointmentData {
  date: string
  time: string
  doctor: Doctor
  patient?: Patient
}

const appointmentData = ref<AppointmentData | null>(null)
const appointmentId = ref<string>('')

const showAddressMap = ref(false)
const selectedAddress = ref('')

// 格式化日期
const formatDate = (dateString: string) => {
  const date = new Date(dateString)
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const weekdays = ['周日', '周一', '周二', '周三', '周四', '周五', '周六']
  const weekday = weekdays[date.getDay()]
  
  return `${year}年${month}月${day}日 ${weekday}`
}

// 格式化时间
const formatTime = (timeString: string) => {
  const timeSlot = timeString.split('-')[1] // 获取时间段的后半部分
  const [hour, minute] = timeSlot.split(':')
  const hourNum = parseInt(hour)
  
  if (hourNum < 12) {
    return `${hour}:${minute} AM`
  } else if (hourNum === 12) {
    return `${hour}:${minute} PM`
  } else {
    return `${hourNum - 12}:${minute} PM`
  }
}

// 跳转到支付页面
const goToPayment = () => {
  const amount = 50 // 默认支付金额，实际应该从后端获取
  
  // 保存预约数据到localStorage，供支付页面使用
  if (appointmentData.value) {
    localStorage.setItem('paymentData', JSON.stringify({
      appointmentId: appointmentId.value,
      appointmentData: appointmentData.value,
      amount: amount
    }))
    // 保存支付金额
    localStorage.setItem('paymentAmount', amount.toString())
  }
  
  // 带上金额参数跳转到支付页面
  router.push({
    path: '/payment',
    query: {
      amount: amount.toString()
    }
  })
}

// 查看预约
const viewAppointments = () => {
  // 这里可以跳转到预约列表页面
  showToast('功能开发中...')
}

// 处理地址选择
const handleAddressSelect = (address: any) => {
  selectedAddress.value = address.address
  localStorage.setItem('deliveryAddress', JSON.stringify(address))
}

// 轻提示
const showToast = (message: string) => {
  const toast = document.createElement('div')
  toast.className = 'toast-message'
  toast.textContent = message
  document.body.appendChild(toast)
  
  setTimeout(() => toast.classList.add('show'), 10)
  setTimeout(() => {
    toast.classList.remove('show')
    setTimeout(() => {
      if (document.body.contains(toast)) {
        document.body.removeChild(toast)
      }
    }, 300)
  }, 3000)
}

// 图片加载错误处理
const handleImageError = (event: Event) => {
  const img = event.target as HTMLImageElement
  img.src = ''
}

// 生成预约编号
const generateAppointmentId = () => {
  const timestamp = Date.now()
  const random = Math.floor(Math.random() * 1000)
  return `AP${timestamp}${random}`
}

onMounted(() => {
  // 获取预约数据
  const savedAppointmentData = localStorage.getItem('appointmentData')
  if (savedAppointmentData) {
    appointmentData.value = JSON.parse(savedAppointmentData)
  }
  
  // 生成预约编号
  appointmentId.value = generateAppointmentId()

  // 加载保存的地址
  const savedAddress = localStorage.getItem('deliveryAddress')
  if (savedAddress) {
    try {
      const address = JSON.parse(savedAddress)
      selectedAddress.value = address.address
    } catch (error) {
      console.error('解析地址数据失败:', error)
    }
  }
})
</script>

<style scoped>
.appointment-confirm-page {
  min-height: 100vh;
  background: #f8f9fa;
  padding-bottom: 100px;
}

.header {
  background: #1877F2;
  padding: 0 20px;
  padding-top: env(safe-area-inset-top);
}

.header-content {
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: 56px;
}

.back-btn, .home-btn {
  width: 40px;
  height: 40px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  border-radius: 8px;
  transition: all 0.2s;
}

.back-btn:hover, .home-btn:hover {
  background: rgba(255, 255, 255, 0.1);
}

.header-title {
  color: #fff;
  font-size: 18px;
  font-weight: 600;
  flex: 1;
  text-align: center;
}

.content {
  padding: 20px;
  text-align: center;
}

.success-icon {
  margin-bottom: 20px;
}

.title {
  font-size: 24px;
  font-weight: 700;
  color: #333;
  margin: 0 0 8px 0;
}

.subtitle {
  font-size: 16px;
  color: #666;
  margin: 0 0 32px 0;
}

/* 预约信息卡片 */
.appointment-info {
  margin-bottom: 24px;
}

.info-card {
  background: white;
  border-radius: 12px;
  padding: 20px;
  margin-bottom: 16px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.08);
  text-align: left;
}

.info-card h3 {
  font-size: 16px;
  font-weight: 600;
  color: #333;
  margin: 0 0 16px 0;
}

/* 医生信息 */
.doctor-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.doctor-avatar {
  width: 50px;
  height: 50px;
  border-radius: 50%;
  overflow: hidden;
  background: linear-gradient(135deg, #00D4FF 0%, #5B73FF 100%);
  display: flex;
  align-items: center;
  justify-content: center;
}

.doctor-avatar img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.doctor-details h4 {
  font-size: 16px;
  font-weight: 600;
  color: #333;
  margin: 0 0 4px 0;
}

.doctor-details p {
  font-size: 14px;
  color: #666;
  margin: 0 0 2px 0;
}

/* 时间信息 */
.time-info {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.date-display, .time-display {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 16px;
  color: #333;
  font-weight: 500;
}

/* 就诊人信息 */
.patient-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.patient-avatar {
  width: 50px;
  height: 50px;
  border-radius: 50%;
  overflow: hidden;
  background: linear-gradient(135deg, #00D4FF 0%, #5B73FF 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;
}

.patient-avatar img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.patient-details h4 {
  font-size: 16px;
  font-weight: 600;
  color: #333;
  margin: 0 0 4px 0;
}

.patient-details p {
  font-size: 14px;
  color: #666;
  margin: 0 0 2px 0;
}

/* 预约编号 */
.appointment-id {
  font-size: 18px;
  font-weight: 600;
  color: #1877F2;
  font-family: 'Courier New', monospace;
}

/* 注意事项 */
.notice-card {
  background: white;
  border-radius: 12px;
  padding: 20px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.08);
  text-align: left;
}

.notice-card h3 {
  font-size: 16px;
  font-weight: 600;
  color: #333;
  margin: 0 0 16px 0;
}

.notice-list {
  list-style: none;
  padding: 0;
  margin: 0;
}

.notice-list li {
  font-size: 14px;
  color: #666;
  margin-bottom: 8px;
  padding-left: 20px;
  position: relative;
}

.notice-list li:before {
  content: "•";
  color: #1877F2;
  font-weight: bold;
  position: absolute;
  left: 0;
}

.notice-list li:last-child {
  margin-bottom: 0;
}

/* 底部按钮 */
.bottom-button {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 16px;
  background: #fff;
  border-top: 1px solid #f0f0f0;
  z-index: 100;
}

.pay-btn {
  width: 100%;
  height: 48px;
  background: #1877F2;
  color: #fff;
  border: none;
  border-radius: 8px;
  font-size: 16px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.2s;
  margin-bottom: 12px;
}

.pay-btn:hover {
  background: #1565c0;
}

.secondary-buttons {
  display: flex;
  gap: 12px;
}

.home-btn-secondary {
  flex: 1;
  height: 40px;
  background: #f5f5f5;
  color: #666;
  border: 1px solid #ddd;
  border-radius: 8px;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.2s;
}

.home-btn-secondary:hover {
  background: #e0e0e0;
  color: #333;
}

.view-appointments-btn {
  flex: 1;
  height: 40px;
  background: #f5f5f5;
  color: #666;
  border: 1px solid #ddd;
  border-radius: 8px;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.2s;
}

.view-appointments-btn:hover {
  background: #e0e0e0;
  color: #333;
}

/* 轻提示 */
.toast-message {
  position: fixed;
  top: 20px;
  left: 50%;
  transform: translateX(-50%);
  background-color: rgba(0, 0, 0, 0.7);
  color: white;
  padding: 12px 24px;
  border-radius: 8px;
  font-size: 14px;
  font-weight: 500;
  z-index: 10000;
  opacity: 0;
  transition: opacity 0.3s ease-in-out;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
  white-space: nowrap;
}

.toast-message.show {
  opacity: 1;
}

/* 地址样式 */
.address-info {
  display: flex;
  align-items: center;
  gap: 12px;
  cursor: pointer;
  padding: 8px 0;
}

.address-icon {
  color: #1877F2;
}

.address-content {
  flex: 1;
}

.address-detail {
  font-size: 16px;
  color: #333;
  font-weight: 500;
}

.address-arrow {
  color: #999;
}

/* 响应式设计 */
@media (max-width: 480px) {
  .content {
    padding: 16px;
  }
  
  .title {
    font-size: 20px;
  }
  
  .subtitle {
    font-size: 14px;
  }
  
  .info-card {
    padding: 16px;
  }
  
  .notice-card {
    padding: 16px;
  }
}
</style> 